
import pdb

from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from psd.register.models import RegRecord, Event
from datetime import date


@login_required
def show_me_all(request):
    user = request.user
    reg_list = RegRecord.objects.filter(psdid=user.username)

    # so ugly!
    today = date.today()
    reg_list_cur = []
    reg_list_past = []
    regged_evts = set()
    for r in reg_list:
        r.eventrec = Event.objects.get(event=r.event)
        if r.eventrec.date < today:
            reg_list_past.append( r)
        else:
            reg_list_cur.append(r)
        regged_evts.add( r.event )
        
    # get all open events
    evts = Event.objects.all()
    open_events = []
    for evt in evts:
        if evt.date >= today and not evt.event in regged_evts:
            open_events.append( evt )
            
    if reg_list:
        if reg_list[0].is_group:
            group_or_individual = "group"
        else:
            group_or_individual = "individual"
        return render_to_response('show_me_all.html', locals(),  
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('user_not_found.html', {}, context_instance=RequestContext(request))


@login_required
def show_me(request, event_name):
    user = request.user
    reg_list = RegRecord.objects.filter(psdid=user.username).filter(event=event_name)

    if reg_list:
        return render_to_response('show_me.html', {'reg': reg_list[0]},  context_instance=RequestContext(request))
    else:
        return render_to_response('user_not_found.html', {}, context_instance=RequestContext(request))



def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response('mylogin.html',{'state':state, 'username': username})
